package top.igotcha.chapter.chapter7.ThreadPoolExecutor01;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @author Gotcha
 * @date 2021/3/10
 * @describe 自定义线程池
 */
@Slf4j(topic = "自定义线程池")
public class ThreadPool01 {
    //任务队列
    private BlockingQueue<Runnable> taskQueue;

    //线程集合
    private HashSet<Worker> workers = new HashSet();

    //核心线程数
    private int coreSize;

    //获取任务的超时时间
    private long timeout;

    //时间单位
    private TimeUnit unit;

    //拒绝策略
    private RejectPolicy<Runnable> rejectPolicy;

    //执行任务
    public void execute(Runnable task){
        //当任务数没有超过coreSize时，直接交给worker对象执行
        //当任务数超过coreSize时，进入阻塞队列
        synchronized (workers) {
            if (workers.size() < coreSize){
                Worker worker = new Worker(task);
                log.debug("新增 worker{},处理 任务{}",worker,task);
                worker.start();
                workers.add(worker);
            } else {
                //taskQueue.put(task);
                //1.死等
                //2.带超时的等待
                //3.让调用者放弃任务执行
                //4.让调用者抛出异常
                //5.让调用者自己执行任务
                taskQueue.tryPut(rejectPolicy,task);
            }
        }
    }

    public ThreadPool01(int coreSize, long timeout, TimeUnit unit,int queueCapcity,RejectPolicy<Runnable> rejectPolicy) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.unit = unit;
        this.taskQueue = new BlockingQueue<>(queueCapcity);
        this.rejectPolicy = rejectPolicy;
    }

    class Worker extends Thread{
        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
            //执行任务
                //1.当task不为空直接执行
                //2.当task执行完毕，从任务队列中获取任务继续执行
                //while (task != null || (task = taskQueue.take()) != null ){
                while (task != null || (task = taskQueue.take(timeout,unit)) != null ){
                    try {
                        log.debug("正在执行{}任务",task);
                        task.run();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        task = null;
                    }
                }
                synchronized (workers){
                    log.debug("worker{} 被移除",this);
                    workers.remove(this);
                }
        }
    }
}




